<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Fenxiao extends Stourweb_Controller
{
    private $_level_num=3;
    public function before()
    {
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $this->_level_num=empty($level_num)?3:$level_num;
        $this->assign('level_num',$this->_level_num);
        parent::before();
    }

    public function action_list()
    {
        $action = $this->params['action'];
        if (empty($action))  //显示线路列表页
        {
            $group_list = DB::select()->from('fenxiao_group')->execute()->as_array();
            $rank_list = DB::select()->from('fenxiao_rank')->execute()->as_array();

            $this->assign('group_list',$group_list);
            $this->assign('rank_list',$rank_list);
            $this->display('admin/fenxiao/list');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $status = $_GET['status'];
            $fxrankid = $_GET['fxrankid'];
            $fxgroupid = $_GET['fxgroupid'];
            $isfrozen = $_GET['isfrozen'];
            $sort = json_decode(Arr::get($_GET, 'sort'), true);
            $order = 'order by a.fxjointime desc';
            $webid = empty($webid) ? -1 : $webid;
            $keyword = Common::getKeyword($keyword);
            if ($sort[0]['property'])
            {
                $prefix = '';
                if ($sort[0]['property'] == 'fxjointime')
                {
                    $prefix = 'a.';
                }
                else if ($sort[0]['property'] == 'subnum')
                {
                    $prefix = 'b.';
                }
                else if ($sort[0]['property'] == 'status')
                {
                    $prefix = 'a.';
                }

                $order = 'order by ' . $prefix . $sort[0]['property'] . ' ' . $sort[0]['direction'] . ',a.fxjointime desc';

                if ($sort[0]['property'] == 'money')
                {
                    $order = 'order by (c.money-c.money_frozen) ' . $sort[0]['direction'] . ',a.fxjointime desc';
                }

            }
            $w = " where a.id is not null";
            $w .= empty($keyword) ? '' : " and (c.mobile like '%{$keyword}%' or c.mid like '%{$keyword}%' or c.email like '%{$keyword}%' or c.nickname like '%{$keyword}%')";
            if(!empty($status) || $this->is_zero($status))
            {
                $w.=" and a.status={$status} ";
            }
            if(!empty($isfrozen) || $this->is_zero($isfrozen))
            {
                $w.=" and a.isfrozen={$isfrozen} ";
            }
            if(!empty($fxrankid))
            {
                $w.=" and a.fxrankid={$fxrankid} ";
            }
            if(!empty($fxgroupid) || $this->is_zero($fxgroupid))
            {
                $w.=" and a.fxgroupid={$fxgroupid} ";
            }

            $sql = "select a.*,c.* from  sline_fenxiao a inner join sline_member c on a.memberid=c.mid  $w $order limit {$start},{$limit}";
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_fenxiao a inner join sline_member c on a.memberid=c.mid  $w")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();

            $groups=ORM::factory('fenxiao_group')->get_all();
            array_unshift($groups,['id' => 0,'title'=>'默认分组']);

            foreach($list as &$row)
            {
                $row['id']=$row['mid'];
                $row['consumeamount']= Model_Fenxiao::get_consume_amount($row['mid']);
                $row['account']=$row['regtype']==1?$row['email']:$row['mobile'];
				$row['account']=empty($row['account'])?$row['email']:$row['account'];
                $row['account']=empty($row['account'])?$row['nickname']:$row['account'];
                $sub_mids = Model_Fenxiao::get_sub_mids($row['memberid'],$this->_level_num);
                $row['subnum']=empty($sub_mids)?0:count($sub_mids);

//                St_Functions::writeLog($row['fxgroupid'],__LINE__);
//                St_Functions::writeLog($groups,__LINE__);

                foreach ($groups as $group) {
                    if($group['id']==$row['fxgroupid']){
                         $groupname =$group['title'];
                    }
                }
                $row['groupname']=$groupname;

                $row['subordernum'] = Model_Fenxiao::get_sub_order_num($row['memberid'],$this->_level_num);
                $row['fxjointime']= !empty($row['fxjointime'])? date('Y-m-d H:i',$row['fxjointime']):'';
                $row['verifytime'] = !empty($row['verifytime'])? date('Y-m-d H:i',$row['verifytime']):'';
                $row['rankname']= Model_Fenxiao_Rank::get_name($row['fxrankid']);
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {
        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {
            $id=Arr::get($_POST,'id');
            $field=Arr::get($_POST,'field');
            $val=Arr::get($_POST,'val');
            $model=ORM::factory('fenxiao')->where('memberid','=',$id)->find();
            $curtime=time();
            if($model->id)
            {
                $model->$field=$val;
                if($field=='isfrozen')
                {
                    if($val==1)
                        $model->frozentime=$curtime;
                    else
					{
                        $model->unfrozentime=$curtime;
						$model->fxlogintime=$curtime;
					}
                }
                $model->save();
                if($model->saved())
                    echo 'ok';
                else
                    echo 'no';
            }

        }
    }
    //查看编辑分销商
    public function action_edit()
    {

        $mid=$this->params['memberid'];
        $memberModel=ORM::factory('member',$mid);

        $fxModel=ORM::factory('fenxiao')->where('memberid','=',$mid)->find();
        if(!$memberModel->loaded())
            exit('错误的ID');

        $info=$memberModel->as_array();
        $fxInfo=$fxModel->as_array();
        $info['account']=$info['regtype']==1?$info['email']:$info['mobile'];
        $info['account']=empty($info['account'])?$info['nickname']:$info['account'];
        $fxInfo['fxjointime']= !empty($fxInfo['fxjointime'])? date('Y-m-d',$fxInfo['fxjointime']):'';
        $submids = Model_Fenxiao::get_sub_mids($mid);
        $fxInfo['subnum'] = !empty($submids)?count($submids):0;
        $fxInfo['subordernum'] = Model_Fenxiao::get_sub_order_num($mid,$this->_level_num);
        $fxInfo['suborder_amount']= Model_Fenxiao::get_sub_order_totalprice($mid);
        $fxInfo['fxrank_name'] = Model_Fenxiao_Rank::get_name($fxInfo['fxrankid']);

        $groups=ORM::factory('fenxiao_group')->get_all();
        $ranks=ORM::factory('fenxiao_rank')->get_all();

        $this->assign('ranks',$ranks);
        $this->assign('memberid',$mid);
        $this->assign('groups',$groups);
        $this->assign('info',$info);
        $this->assign('fxinfo',$fxInfo);
        $this->display('admin/fenxiao/edit');
    }

    //下级分销商列表
    public function action_submember()
    {
        $action = $this->params['action'];
        if (empty($action))  //显示线路列表页
        {
            $memberid = $_GET['memberid'];
            $sub_mids = Model_Fenxiao::get_sub_mids($memberid,$this->_level_num);
            $first_sub_mids = Model_Fenxiao::get_sub_mids($memberid, 1);

            $sub_total = !empty($sub_mids)?count($sub_mids):0;
            $sub_first_total = !empty($first_sub_mids)?count($first_sub_mids):0;
            $sub_second_total =  count(Model_Fenxiao::get_sub_mids($memberid, 2,true));
            $sub_third_total =  count(Model_Fenxiao::get_sub_mids($memberid, 3,true));

            $first_parent_member = $this->get_ancestor_member($memberid,1);
            $second_parent_member = $this->get_ancestor_member($memberid,2);
            $third_parent_member = $this->get_ancestor_member($memberid,3);





            $this->assign('sub_total',$sub_total);
            $this->assign('sub_first_total',$sub_first_total);
            $this->assign('sub_second_total',$sub_second_total);
            $this->assign('sub_third_total',$sub_third_total);

            $this->assign('first_parent_member',$first_parent_member);
            $this->assign('second_parent_member',$second_parent_member);
            $this->assign('third_parent_member',$third_parent_member);

            $this->assign('memberid',$memberid);
            $this->display('admin/fenxiao/submember');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $sort = json_decode(Arr::get($_GET, 'sort'), true);
            $keyword = Arr::get($_GET, 'keyword');
            $group = $_GET['group'];
            $memberid = $_GET['memberid'];
            $order = 'order by a.fxjointime desc';
            if ($sort[0]['property'])
            {
                $prefix = '';
                $order = 'order by ' . $prefix . $sort[0]['property'] . ' ' . $sort[0]['direction'] . ',a.fxjointime desc';
            }
            $sub_mids = Model_Fenxiao::get_sub_mids($memberid,$this->_level_num);

            $first_sub_mids = Model_Fenxiao::get_sub_mids($memberid, 1);
            if($group)
            {
                $sub_mids =  Model_Fenxiao::get_sub_mids($memberid,$group,true);
            }

            if(empty($sub_mids))
            {
                $result = array();
                $result['total'] = 0;
                $result['lists'] = array();
                $result['success'] = true;
               echo json_encode($result);
                return;
            }

            $order_by = "";
            switch($order)
            {
                case 1:
                    $order_by = " order by ifnull(b.total,0) desc ";
                    break;
                case 2:
                    $order_by = " order by ifnull(b.total,0) asc ";
                    break;
                case 3:
                    $order_by = " order by a.fxjointime desc ";
                    break;
                case 4:
                    $order_by = " order by a.fxrankid desc ";
                    break;
            }

            $w  = " where a.memberid in (".implode(',',$sub_mids).")";
            if(!empty($keyword))
            {
                $w.= " and (c.nickname like '{$keyword}%' or c.mobile like '{$keyword}%' or c.email like '{$keyword}%') ";
            }


            $sql = "select a.memberid,a.fxjointime,a.fxrankid,a.fxgroupid,b.total,a.id from sline_fenxiao a
inner join sline_member c on a.memberid=c.mid
left join (select sum(amount) as total,fxmemberid from sline_fenxiao_record where memberid=".$memberid." and type=0 group by fxmemberid) b on a.memberid=b.fxmemberid {$w} {$order_by} limit {$start},{$limit}";


           $sql_num = "select count(*) as num from sline_fenxiao a
inner join sline_member c on a.memberid=c.mid
left join (select sum(amount) as total,fxmemberid from sline_fenxiao_record where memberid=".$memberid." and type=0 group by fxmemberid) b on a.memberid=b.fxmemberid {$w}";
            $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
            $num = DB::query(Database::SELECT,$sql_num)->execute()->get('num');
            foreach($list as &$row)
            {
                $member_info = Model_Member::get_member_byid($row['memberid']);
                $row['nickname'] = $member_info['nickname'];
                $row['account']=$member_info['mobile'];
                $row['account']=empty($row['account'])?$member_info['email']:$row['account'];
                $row['account']=empty($row['account'])?$member_info['nickname']:$row['account'];
                $row['litpic'] = $member_info['litpic'];
                $row['fxrank_name'] = Model_Fenxiao_Rank::get_name($row['fxrankid']);
                $row['fxgroup_name'] = Model_Fenxiao_Group::get_name($row['fxgroupid']);
                $row['sub_num'] = count(Model_Fenxiao::get_sub_mids($row['memberid'],1));
                $row['fxjointime'] = date('Y-m-d',$row['fxjointime']);
                $row['sub_level'] = Model_Fenxiao::get_rank($memberid,$row['memberid']);
                $row['total'] = empty($row['total'])?0:$row['total'];
                $row['total'] = round($row['total'],2);

            }

            $result['total'] = $num;
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
    }

    //下级订单
    public function action_suborder()
    {
        $action = $this->params['action'];

        if (empty($action))  //显示线路列表页
        {
            $memberid = $_GET['memberid'];

            $sub_num = Model_Fenxiao::new_get_sub_order_num($memberid,$this->_level_num);
            $sub_finish_num = Model_Fenxiao::new_get_sub_order_num($memberid,0,5);
            $total_profit = round(Model_Fenxiao::get_total_profit($memberid),2);
            $sub_order_totalprice = round(Model_Fenxiao::new_get_sub_order_totalprice($memberid),2);

            $status_names = Model_Member_Order::$order_status;
            $products = Model_Fenxiao::get_fenxiao_product();

            $this->assign('status_names',$status_names);
            $this->assign('products',$products);

            $this->assign('sub_num',$sub_num);
            $this->assign('sub_finish_num',$sub_finish_num);
            $this->assign('total_profit',$total_profit);
            $this->assign('sub_order_totalprice',$sub_order_totalprice);
            $this->assign('memberid', $memberid);
            $this->display('admin/fenxiao/suborder');
        }
        else if($action=='read')
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $memberid = $_GET['memberid'];
            $keyword = $_GET['keyword'];
            $group = intval($_GET['group']);
            $typeid = $_GET['typeid'];
            $status = $_GET['status'];


            $fenxiao_info = DB::select()->from('fenxiao')->where('memberid','=',$memberid)->execute()->current();

            switch ($group) {
                case 1:
                    $all_fenxiandata = Db::query(1,"select order_id from sline_fenxiao_data where memberid1={$memberid}")->execute()->as_array();
                    break;
                case 2:
                    $all_fenxiandata = Db::query(1,"select order_id from sline_fenxiao_data where  memberid2={$memberid} ")->execute()->as_array();
                    break;
                case 3:
                    $all_fenxiandata = Db::query(1,"select order_id from sline_fenxiao_data where memberid3={$memberid}")->execute()->as_array();
                    break;
                default:
                    $all_fenxiandata = Db::query(1,"select order_id from sline_fenxiao_data where memberid1={$memberid} or memberid2={$memberid} or memberid3={$memberid}")->execute()->as_array();
                    break;
            }
            $order_ids = array_column($all_fenxiandata,'order_id');
            if(empty($order_ids))
            {
                $result = array();
                $result['total'] = 0;
                $result['lists'] = array();
                $result['success'] = true;
                echo json_encode($result);
                return;
            }

            $w = " where a.id in (".implode(',',$order_ids).") ";
            if(!empty($typeid))
            {
                $w.=" and a.typeid={$typeid} ";
            }
            if(!empty($keyword))
            {
                $w.=" and (m.nickname like '%{$keyword}%' or m.mobile like '%{$keyword}%' ) ";
            }

            if(!empty($status) || $this->is_zero($status))
            {
                $w.=" and a.status='{$status}' ";
            }

            $order_by = " order by a.addtime desc";

            $sql = " select a.*,b.amount as fenxiao_amount from sline_member_order a left join sline_fenxiao_record b on a.id=b.orderid and (b.memberid is null or b.memberid=".$memberid.") left join sline_member m on m.mid=a.memberid  {$w} {$order_by} limit {$start},{$limit}";

            $sql_num = "select count(*) as num from sline_member_order a left join sline_fenxiao_record b on a.id=b.orderid and (b.memberid is null or b.memberid=".$memberid.") left join sline_member m on m.mid=a.memberid {$w}";
            $num = DB::query(Database::SELECT,$sql_num)->execute()->get('num');
            $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
            foreach ($list as &$v)
            {
                $model = ORM::factory('model', $v['typeid']);
                $table = $model->maintable;
                if ($table)
                {
                    $py = empty($model->correct) ? $model->pinyin : $model->correct;
                    $info = ORM::factory($table, $v['productautoid'])->as_array();
                    $out = $info;
                    $v['url'] = St_Functions::get_web_url($info['webid']) . "/{$py}/show_{$info['aid']}.html";
                    $v['type_name'] = $model->modulename;
                }
                $v['totalprice'] = Model_Member_Order::order_total_price($v['id'],$v);

                $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'],$fenxiao_info['fxgroupid']);
                $rank = Model_Fenxiao::get_rank($memberid,$v['memberid']);
                $rank_index=$rank-1;
                $v['commission_type'] = $commission_type;
                if($commission_type==1)
                {
                    $commission_rate = Model_Fenxiao::get_commission_rate($v['typeid'],$v['productautoid'],$fenxiao_info['fxgroupid']);
                    $v['commission'] =$commission_rate[$rank_index]*100;
                    $v['commission'] = empty($v['commission'])?0:$v['commission'];
                    $v['commission'] .='%';
                }
                else
                {
                    $commission_cash = Model_Fenxiao::get_commission_cash($v['typeid'],$v['productautoid'],$fenxiao_info['fxgroupid']);
                    $v['commission'] = $commission_cash[$rank_index];
                    $v['commission'] = empty($v['commission'])?0:$v['commission'];
                }
                $member_info = Model_Member::get_member_byid($v['memberid']);
                $v['member'] = $member_info;
                $v['member_nickname'] = $member_info['nickname'];

                $parent_fenxiao = Model_Fenxiao::get_ancestor_fenxiao($v['memberid'],1);
                $v['parent_member'] = Model_Member::get_member_byid($parent_fenxiao['memberid']);
                $v['parent_nickname']  = $v['parent_member']['nickname'];

                $v['addtime'] = date('Y-m-d H:i',$v['addtime']);
                $v['fenxiao_amount'] = empty($v['fenxiao_amount'])?0:$v['fenxiao_amount'];
                $v['status_name'] = Model_Member_Order::get_status_name($v['status']);
            }
            $result['total'] = $num;
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
    }

    //返佣记录
    public function action_record()
    {
        $action = $this->params['action'];

        if (empty($action))  //显示线路列表页
        {
            $memberid = $_GET['memberid'];
            $total_profit = Model_Fenxiao::get_total_profit($memberid);
            $total_profit = round($total_profit,2);
            $member = DB::select()->from('member')->where('mid','=',$memberid)->execute()->current();
            $member['money_left'] = $member['money']-$member['money_frozen'];
            $this->assign('memberid', $memberid);
            $this->assign('total_profit',$total_profit);
            $this->assign('member',$member);
            $this->display('admin/fenxiao/record');
        }
        else if($action=='read')
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $memberid = $_GET['memberid'];

            $w = " where a.memberid='{$memberid}' and a.type=0 ";
            $sql = "select a.*,b.description from sline_fenxiao_record a left join sline_member_cash_log b on a.memberid=b.memberid and a.orderid=b.orderid and b.type=0 {$w} order by addtime desc limit {$start},{$limit}";
            $sql_num = "select count(*) as num from sline_fenxiao_record a {$w}";
            $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
            $num = DB::query(Database::SELECT,$sql_num)->execute()->get('num');

            foreach($list as &$row)
            {
                $row['addtime'] = date('Y-m-d H:i',$row['addtime']);
            }

            $result['total'] = $num;
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
    }

    public function action_ajax_save()
    {
        $id=$_POST['id'];
        $groupid=$_POST['groupid'];
        $status=$_POST['status'];
        $fxrankid=$_POST['fxrankid'];
        $isfrozen = $_POST['isfrozen'];
        $model=ORM::factory('fenxiao',$id);
        if(!$model->loaded())
        {
            echo json_encode(array('status'=>false,'msg'=>'ID错误'));
            return;
        }
        $curtime=time();

        $groupid = empty($groupid)?0:$groupid;
        $model->fxgroupid=$groupid;
        $model->isfrozen = $isfrozen;

        if($model->status!=-1)
        {
            if ($model->status != $status)
                $model->verifytime = $curtime;
            $model->status = $status;
            if($status==1)
            {
                $fxrankid = Model_Fenxiao::get_rankid($model->memberid);
                $model->fxrankid=$fxrankid;

            }
        }

       // $model->fxrankid=$fxrankid;
        $model->save();
        echo json_encode(array('status'=>true,'msg'=>'修改完成'));
    }

    /**
     * @function 导出excel页面
     */
    public function action_excel(){

        $group_list = DB::select()->from('fenxiao_group')->execute()->as_array();
        $rank_list = DB::select()->from('fenxiao_rank')->execute()->as_array();

        $this->assign('group_list',$group_list);
        $this->assign('rank_list',$rank_list);
        $this->assign('params',$_GET);
        $this->display('admin/fenxiao/excel');
    }

    /**
     * @function 导出excel
     */
    public function action_genexcel(){

        // 时间
        $timetype = $this->params['timetype'];
        $starttime = empty($_GET['starttime'])? null:strtotime($_GET['starttime'].' 00:00:00');
        $endtime =empty($_GET['endtime'])?null: strtotime($_GET['endtime'].' 23:59:59');

        $time_arr = array();
        switch ($timetype)
        {
            case 1:
                $time_arr = St_Functions::back_get_time_range(1);
                break;
            case 2:
                $time_arr = St_Functions::back_get_time_range(2);
                break;
            case 3:
                $time_arr = St_Functions::back_get_time_range(3);
                break;
            case 5:
                $time_arr = St_Functions::back_get_time_range(5);
                break;
            case 6:
                $time_arr = array($starttime, $endtime);
                break;
        }
        $start_time = $time_arr[0];
        $end_time = $time_arr[1];
        $status = Arr::get($_GET, 'status');
        $fxrankid = Arr::get($_GET, 'fxrankid');
        $fxgroupid = Arr::get($_GET, 'fxgroupid');
        $isfrozen = Arr::get($_GET, 'isfrozen');
        $timetarget = Arr::get($_GET, 'timetarget', 0);
        $order = 'order by a.fxjointime desc';

        $w = " where a.id is not null";
        if(!empty($status) || $this->is_zero($status))
        {
            $w.=" and a.status={$status} ";
        }
        if(!empty($isfrozen) || $this->is_zero($isfrozen))
        {
            $w.=" and a.isfrozen={$isfrozen} ";
        }
        if(!empty($fxrankid))
        {
            $w.=" and a.fxrankid={$fxrankid} ";
        }
        if(!empty($fxgroupid) || $this->is_zero($fxgroupid))
        {
            $w.=" and a.fxgroupid={$fxgroupid} ";
        }
        if(empty($timetarget))
        {
            if (!empty($start_time)) {
                $w .= " and a.fxjointime>=$start_time";
            }
            if (!empty($end_time)) {
                $w .= " and a.fxjointime<=$end_time";
            }
        }
        else if($timetarget==1)
        {
            if (!empty($start_time)) {
                $w .= " and a.verifytime>=$start_time";
            }
            if (!empty($end_time)) {
                $w .= " and a.verifytime<=$end_time";
            }
        }

        $sql = "select a.*,c.* from  sline_fenxiao a inner join sline_member c on a.memberid=c.mid  $w $order";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        $statusArr = array(-1 => '未申请', 0 => '待审核', 1 => '通过', 2 => '不通过');
        foreach($list as &$row)
        {
            $row['consumeamount']= Model_Fenxiao::get_consume_amount($row['mid']);
            $row['account']=$row['regtype']==1?$row['email']:$row['mobile'];
            $row['account']=empty($row['account'])?$row['email']:$row['account'];
            $row['account']=empty($row['account'])?$row['nickname']:$row['account'];
            $sub_mids = Model_Fenxiao::get_sub_mids($row['memberid'],$this->_level_num);
            $row['subnum']=empty($sub_mids)?0:count($sub_mids);
            $row['subordernum'] = Model_Fenxiao::get_sub_order_num($row['memberid'],$this->_level_num);
            $row['fxjointime']= !empty($row['fxjointime'])? date('Y-m-d H:i',$row['fxjointime']):'';
            $row['verifytime'] = !empty($row['verifytime'])? date('Y-m-d H:i',$row['verifytime']):'';
            $row['rankname']= Model_Fenxiao_Rank::get_name($row['fxrankid']);
            $row['statusname']= isset($statusArr[$row['status']]) ? $statusArr[$row['status']] : '';
        }
        $excel = $this->gene_excel_table($list);
        $filename = date('Ymdhis');
        ob_end_clean();//清除缓冲区
        header('Pragma:public');
        header('Expires:0');
        header('Content-Type:charset=utf-8');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header('Content-Disposition:attachment;filename=' . $filename . ".xls");
        header('Content-Transfer-Encoding:binary');
        echo $excel;
        exit();
    }

    /**
     * @function 导出分销人员表
     * @param $order_list
     * @return string
     */
    protected function gene_excel_table($order_list)
    {

        $table = "<table border='1'><tr>";
        $table .= "<td>昵称</td>";
        $table .= "<td>账号</td>";
        $table .= "<td>账户余额</td>";
        $table .= "<td>推广订单数</td>";
        $table .= "<td>直属下级数</td>";
        $table .= "<td>成为分销商时间</td>";
        $table .= "<td>审核状态</td>";
        $table .= "<td>审核时间</td>";
        $table .= "<td>分销商等级</td>";
        $table .= "<td>冻结状态</td>";
        $table .= "</tr>";
        foreach ($order_list as $row)
        {
            $nickname = strval($row['nickname']);
            $account = strval($row['account']);

            $table .= "<tr>";
            $table .= "<td>{$nickname}</td>";
            $table .= "<td>{$account}</td>";
            $table .= "<td>{$row['money']}</td>";
            $table .= "<td>{$row['subordernum']}</td>";
            $table .= "<td>{$row['subnum']}</td>";
            $table .= "<td>{$row['fxjointime']}</td>";
            $table .= "<td>{$row['statusname']}</td>";
            $table .= "<td>{$row['verifytime']}</td>";
            $table .= "<td>{$row['rankname']}</td>";
            $table .= "<td>".($row['isfrozen'] == 1 ? "冻结" : "正常")."</td>";
            $table .= "</tr>";
        }

        $table .= "</table>";
        return $table;
    }



   /* public function action_withdraw()
    {
        $action = $this->params['action'];
        if (empty($action))  //显示线路列表页
        {
            $this->assign('kindmenu', $this->_menu);//分类设置项
            $this->display('admin/fenxiao/withdraw');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $sort = json_decode(Arr::get($_GET, 'sort'), true);
            $order = 'order by a.addtime desc';
            $webid = empty($webid) ? -1 : $webid;
            $keyword = Common::getKeyword($keyword);
            if ($sort[0]['property'])
            {
                $prefix = 'a.';
                $order = 'order by ' . $prefix . $sort[0]['property'] . ' ' . $sort[0]['direction'] . ',a.addtime desc';
            }
            $w = " where a.id is not null";//a.fxcode is not null and a.fxcode !=''";
            $w .= empty($keyword) ? '' : " and (b.mobile like '%{$keyword}%' or b.mid like '%{$keyword}%' or b.email like '%{$keyword}%')";
            {
                $sql = "select a.*,b.mobile,b.email,b.regtype from sline_fenxiao_withdraw a left join sline_member b on a.memberid=b.mid $w $order";
            }

            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from sline_fenxiao_withdraw a left join sline_member b on a.memberid=b.mid $w")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as &$row)
            {
                $row['account']=$row['regtype']==1?$row['email']:$row['mobile'];
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {
        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {

        }
    }

    public function action_withdraw_edit()
    {
        $id=$this->params['id'];
        $model=ORM::factory('fenxiao_withdraw',$id);
        if(!$model->loaded())
            exit('错误的ID');
        $info=$model->as_array();
        $memberModel=ORM::factory('member',$info['memberid']);
        $memberInfo=$memberModel->as_array();
        $info['account']=$memberInfo['regtype']==0? $memberInfo['mobile']:$memberInfo['email'];
        $this->assign('info',$info);
        $this->display('admin/fenxiao/withdraw_edit');
    }
    public function action_ajax_withdraw_save()
    {
        $id=$_POST['id'];
        $model=ORM::factory('fenxiao_withdraw',$id);
        $status=$_POST['status'];
        $curtime=time();
        try {
            if (!$model->loaded()) {
               throw new Exception('不存在的ID');
            }
            $fenxiaoModel = ORM::factory('fenxiao')->where('memberid', '=', $model->memberid)->find();
            if (!$fenxiaoModel->loaded())
                throw new Exception('分销商不存在');

            if(($model->status==1 || $model->status==2) && $status!=$model->status)
            {
                throw new Exception('禁止将当前状态改为其他状态');
            }

            $fxamount=floatval($fenxiaoModel->fxamount);
            $widthdrawamount=floatval($model->withdrawamount);
            if($widthdrawamount>$fxamount && $status==1)
            {
                throw new Exception('余额不足');
            }
            $model->status = $status;
            $model->finishtime=$curtime;
            $model->save();
            if ($model->saved()) {
                 if($status==1)
                 {
                     $fenxiaoModel->fxamount=$fxamount-$widthdrawamount;
                     $fenxiaoModel->save();
                     $recordModel=ORM::factory('fenxiao_record');
                     $recordModel->memberid=$model->memberid;
                     $recordModel->type=1;
                     $recordModel->withdrawid=$id;
                     $recordModel->amount=-$widthdrawamount;
                     $recordModel->addtime=$curtime;
                     $recordModel->save();

                 }
            } else {
                throw new Exception('保存失败');
            }
            echo json_encode(array('status'=>true,'msg'=>'保存成功'));
        }catch (Exception $excep)
        {
            echo json_encode(array('status' => false, 'msg' => $excep->getMessage()));
        }

    }
   */
    //判断某数是不是为0
    private function is_zero($val)
    {
        if($val===0 || $val==='0')
        {
            return true;
        }
        return false;
    }

    protected function get_ancestor_member($mid,$grade=1)
    {
        $ancestor_fenxiao = Model_Fenxiao::get_ancestor_fenxiao_info($mid,$grade);
        if(empty($ancestor_fenxiao))
        {
            return null;
        }
        $member_info = Model_Member::get_member_byid($ancestor_fenxiao['memberid']);
        $member_info['nickname']= empty( $member_info['nickname'])? $member_info['mobile']:$member_info['nickname'];
        $member_info['nickname']=empty($member_info['nickname'])?$member_info['email']:$member_info['nickname'];
        return $member_info;
    }

    //确认变更
    public function action_ajax_change_fxcode(){
        try {
            $ids= Arr::get($_POST, 'ids');
            $fid= Arr::get($_POST, 'fid');
            $mid= Arr::get($_POST, 'mid');
            if(!$fid){
                throw new Exception('请选择分销商');
            }
            //新分销商的fxcode
            $fxcode = DB::select('fxcode')->from('fenxiao')->where('id','=',$fid)->execute()->get('fxcode');
            if(!$fxcode){
                throw new Exception('分销商不存在');
            }
            if(!$ids){
                throw new Exception('请选择直接下级');
            }
            if(DB::select('fxcode')->from('fenxiao')->where('memberid','=',$mid)->execute()->get('fxcode')==$fxcode){
                throw new Exception('请选择新的分销商');
            }
            DB::update('fenxiao')->set(array('fxpcode'=>$fxcode))->where('id','in',explode(',',$ids))->execute();
            exit(json_encode(array('status' => true, 'msg' => '修改成功')));
        }catch (Exception $excep) {
            exit(json_encode(array('status' => false, 'msg' => $excep->getMessage())));
        }
    }

    public function action_dialog_change_fxcode(){
        $this->assign('ids', $_REQUEST['ids']);
        $this->assign('mid', $_REQUEST['mid']);
        $num1 = Model_Fenxiao::get_sub_order_num($_REQUEST['mid'],1,5);
        $num2 = Model_Fenxiao::get_sub_order_num($_REQUEST['mid'],1);
        if($num1-$num2>0){
           exit('存在未结算订单');
        }
        $this->display('admin/fenxiao/dialog_change_fxcode');
    }

    public function action_ajax_search_fenxiao(){
        try {
            $mobile= Arr::get($_POST, 'mobile');
            if(!$mobile){
                throw new Exception('请输入手机号码');
            }
            $member = DB::select()->from('member')->where('mobile','=',$mobile)->execute()->current();
            if(!$member){
                throw new Exception('用户不存在');
            }
            $fenxiao=DB::select()->from('fenxiao')->where('memberid','=',$member['mid'])->execute()->current();
            if(!$fenxiao){
                throw new Exception('分销商不存在');
            }
            if($fenxiao['status']!=1){
                throw new Exception('未通过审核');
            }
            exit(json_encode(array('status' => true, 'data' => $member['nickname'],'fid'=>$fenxiao['id'])));
        }catch (Exception $excep) {
            exit(json_encode(array('status' => false, 'msg' => $excep->getMessage())));
        }
    }
}